#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <string>
#include <sstream>


#define LOW 1
#define HIGH 5143

using namespace std;


int main( int argc, char** argv ) {
	IplImage* src;
	
	/** build and compute histogram **/
    int h_bins = 8, s_bins = 8;
    CvHistogram* hist;

	
	int    hist_size[] = { h_bins, s_bins };
	float  h_ranges[]  = { 0, 180 };          // hue is [0,180]
	float  s_ranges[]  = { 0, 255 };
	float* ranges[]    = { h_ranges, s_ranges };
	 
    
	string s000("000"), s00("00"), s0("0");
	for(int i = LOW; i <= HIGH; i++)
	{
		stringstream ss;
		ss << i;
		string is = ss.str();
		string num = i < 10 ? (s000 + is) : ( i < 100 ? ( s00 + is) : (i<1000 ? s0 + is : is));
		string filename = "tempimg/img" + num + ".jpg";		

		if((src=cvLoadImage((char*)filename.c_str(), 1))!= 0) {

			hist = cvCreateHist( 2, hist_size, CV_HIST_ARRAY,ranges, 1);//dims, size, type, range,uniform

			/** Initialize: Compute the HSV image and decompose it into separate planes. **/
			IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 ); 
			cvCvtColor( src, hsv, CV_BGR2HSV ); 
			IplImage* h_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
			IplImage* s_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
			IplImage* v_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
			IplImage* planes[] = { h_plane, s_plane };
			cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );//src,dst1,dst2,dst3

			cvCalcHist( planes, hist, 0, 0 ); //Compute histogram img, hist, accumulate,mask
			cvNormalizeHist( hist, 1.0 );  //Normalize it hist,factor
			
			cvReleaseImage(&src);
			cvReleaseImage(&hsv);
			cvReleaseImage(&h_plane);
			cvReleaseImage(&s_plane);
			cvReleaseImage(&v_plane);

			stringstream sbin;
			sbin << h_bins;
			string outfilename(string("hist")+num+string("_")+string(sbin.str()));
			cvSave((char*)outfilename.c_str(), hist);

			cvReleaseHist(&hist);
		} 
		else {
			printf((char*)filename.c_str());
		}
	    
		

	}
    
}